package com.xerland.tbootstrap;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.xerland.tbootstrap.ui.ExpandableListViewFragment;
import com.xerland.tbootstrap.ui.base.BaseActivity;
import com.xerland.tbootstrap.ui.navigationdrawer.NavigationDrawerFragment;
import com.xerland.tbootstrap.ui.presenters.MainActivityPresenter;
import com.xerland.tbootstrap.ui.recyclerview.QuotesAdapter;
import com.xerland.tbootstrap.ui.views.MainActivityView;
import com.xerland.tbootstrap.utils.UIUtils;

import java.lang.reflect.Field;

import javax.inject.Inject;

public class MainActivity extends BaseActivity implements MainActivityView {

    @Inject
    BootstrapServiceProvider serviceProvider;

    @Inject
    protected MainActivityPresenter presenter;

    @Inject
    protected QuotesAdapter quotesAdapter;

//    @BindView(R.id.voila)
//    Button button;
//    @BindView(R.id.list_of_quotes)
//    protected RecyclerView recyclerView;
//    @BindView(R.id.empty_list)
//    protected TextView emptyListView;

    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle drawerToggle;
    private CharSequence drawerTitle;
    private CharSequence title;
    private NavigationDrawerFragment navigationDrawerFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView();

//        ButterKnife.bind(this);

        getActivityComponent().inject(this);
        presenter.attach(this);
//        presenter.loadQuotes();

//        recyclerView.setLayoutManager(new LinearLayoutManager(this));
//        recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
//        recyclerView.setAdapter(quotesAdapter);
        presenter.checkAuth();
//        showMainView();


    }

//    @OnClick(R.id.voila) void onVoila(){
//        Timber.e("onVoila!");
//        presenter.getQuotes();
//    }


//    @Override
//    public void showQuotes(@NonNull List<EmojitEntity> quoteEntities){
////        Timber.e("in showQuotes");
////        emptyListView.setVisibility(View.GONE);
////        recyclerView.setVisibility(View.VISIBLE);
////        quotesAdapter.setQuoteEntities(quoteEntities);
////        quotesAdapter.notifyDataSetChanged();
//    }

//    @Override
//    public void showQuotesIsEmpty(){
////        recyclerView.setVisibility(View.GONE);
////        emptyListView.setVisibility(View.VISIBLE);
//    }

    @Override
    public void showInternetNotAvailable(){
        Toast.makeText(getApplication(), "Internet not available!",Toast.LENGTH_LONG).show();
    }

    @Override
    public void showMainView() {
        final FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, new ExpandableListViewFragment())//.newInstance()
                .commit();
        setDrawerNvg();
    }

    @Override
    public void setContentView() {
        if(isTablet()) {
            setContentView(R.layout.main_activity_tablet);
        } else {
            setContentView(R.layout.main_activity);
        }
    }

    @Override
    public void showLoginView() {

    }

    public void setDrawerNvg() {
        if(!isTablet()) {
            drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawerToggle = new ActionBarDrawerToggle(
                    this,                    /* Host activity */
                    drawerLayout,           /* DrawerLayout object */
                    R.string.navigation_drawer_open,    /* "open drawer" description */
                    R.string.navigation_drawer_close) { /* "close drawer" description */

                /** Called when a drawer has settled in a completely closed state. */
                public void onDrawerClosed(View view) {
                    getSupportActionBar().setDisplayShowTitleEnabled(false);
//                    getSupportActionBar().setTitle(title);getSupportActionBar().setTitle(title);
                    invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
                    syncState();
                }

                /** Called when a drawer has settled in a completely open state. */
                public void onDrawerOpened(View drawerView) {
                    getSupportActionBar().setDisplayShowTitleEnabled(false);
//                    getSupportActionBar().setTitle(drawerTitle);
                    invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
                    syncState();
                }
            };

            if(!isTablet()) {
                drawerToggle.syncState();
            }

            // Set the drawer toggle as the DrawerListener
            drawerLayout.setDrawerListener(drawerToggle);

            navigationDrawerFragment = (NavigationDrawerFragment)
                    getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);

            // Set up the drawer.
            navigationDrawerFragment.setUp(
                    R.id.navigation_drawer,
                    (DrawerLayout) findViewById(R.id.drawer_layout));
        }
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    private boolean isTablet() {
        return UIUtils.isTablet(this);
    }

//    public void checkAuth() {
//        new SafeAsyncTask<Boolean>() {
//
//            @Override
//            public Boolean call() throws Exception {
//                final BootstrapService svc = serviceProvider.getService(MainActivity.this);
//                return svc != null;
//            }
//
//            @Override
//            protected void onException(final Exception e) throws RuntimeException {
//                super.onException(e);
//                if (e instanceof OperationCanceledException) {
//                    // User cancelled the authentication process (back button, etc).
//                    // Since auth could not take place, lets finish this activity.
//                    finish();
//                }
//            }
//
//            @Override
//            protected void onSuccess(final Boolean hasAuthenticated) throws Exception {
//                super.onSuccess(hasAuthenticated);
////                userHasAuthenticated = true;
//                /*getMvpView().*/showMainView();
////                initScreen();
//            }
//        }.execute();
//    }

    @Override
    protected void onDestroy() {
        fixInputMethodManagerLeak(this);
        super.onDestroy();
    }

    public static void fixInputMethodManagerLeak(Context context) {
        if (context == null) {
            return;
        }
        try {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm == null) {
                return;
            }

            Object obj_get = null;
            Field f_mCurRootView = imm.getClass().getDeclaredField("mCurRootView");
            Field f_mServedView = imm.getClass().getDeclaredField("mServedView");
            Field f_mNextServedView = imm.getClass().getDeclaredField("mNextServedView");

            if (f_mCurRootView.isAccessible() == false) {
                f_mCurRootView.setAccessible(true);
            }
            obj_get = f_mCurRootView.get(imm);
            if (obj_get != null) {
                f_mCurRootView.set(imm, null);
            }

            if (f_mServedView.isAccessible() == false) {
                f_mServedView.setAccessible(true);
            }
            obj_get = f_mServedView.get(imm);
            if (obj_get != null) {
                f_mServedView.set(imm, null);
            }

            if (f_mNextServedView.isAccessible() == false) {
                f_mNextServedView.setAccessible(true);
            }
            obj_get = f_mNextServedView.get(imm);
            if (obj_get != null) {
                f_mNextServedView.set(imm, null);
            }
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

}
